package com.example.system.service;

import com.example.system.controller.dto.SysUserDTO;
import com.example.system.entity.SysUser;
import com.example.system.model.ApiResponse;
import com.example.system.dao.SysUserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

/**
 * author: adnaan
 * create: 2023-11-01 20:17
 * Description:
 */
@Service
public class SysUserService {

    @Autowired
    private SysUserDao sysUserDao;
    public ApiResponse login(String username, String password) {
        if (username == null || password == null || username.isEmpty() || password.isEmpty()) {
            return ApiResponse.error("400", "账号或密码不能为空");
        }

        // 查询用户
        SysUser user = sysUserDao.findByUsername(username);

        // 检查用户是否存在以及密码是否正确
        if (user != null && user.getPassword().equals(password)) {
            // 创建并返回成功响应
            SysUserDTO sysUserDTO = new SysUserDTO();
            sysUserDTO.setUsername(user.getUsername());
            sysUserDTO.setPassword(user.getPassword());

            return ApiResponse.success(sysUserDTO);
        } else {
            // 返回错误响应
            return ApiResponse.error("500", "用户名或密码错误");
        }
    }

    public ApiResponse userDetail(String username) {
        Criteria criteriaName = Criteria.where("username").is(username);
        Criteria orCriteria = new Criteria();
        orCriteria.orOperator(criteriaName);
        Query query = new Query(orCriteria);
        SysUser sysUser = sysUserDao.get(query);
        return ApiResponse.success(sysUser);
    }
}
